package com.fun.seckill.rabbitmq;

import com.fun.seckill.pojo.SeckillMessage;
import com.fun.seckill.pojo.SeckillOrder;
import com.fun.seckill.pojo.User;
import com.fun.seckill.service.IGoodsService;
import com.fun.seckill.service.IOrderService;
import com.fun.seckill.service.ISeckillGoodsService;
import com.fun.seckill.utils.JsonUtil;
import com.fun.seckill.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 消息消费者
 */
@Service
@Slf4j
public class MQReceiver {


    @Autowired
    private IGoodsService itGoodsServicel;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IOrderService itOrderService;

    /**
     * 下单操作
     **/
    @RabbitListener(queues = "seckillQueue")
    public void receive(String message)throws Exception {
        log.info("接收消息：" + message);
        SeckillMessage seckillMessage = JsonUtil.jsonStr2Object(message, SeckillMessage.class);
        Long goodsId = seckillMessage.getGoodId();
        User user = seckillMessage.getUser();
        GoodsVo goodsVo = itGoodsServicel.findGoodsVoByGoodsId(goodsId);
        if (goodsVo.getStockCount() < 1) {
            return;
        }
        //判断是否重复抢购
        SeckillOrder tSeckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodsId);
        if (tSeckillOrder != null) {
            return;
        }
        //下单操作
        itOrderService.secKill(user, goodsVo);
    }

}
